/**
 * @author 艾尼亚尔
 * @date 2025/8/26
 * @description
 */
import {http} from '@/utils/http'
import {objectToQueryString} from '@/utils'
import type {Result} from '@/utils/http/help.ts'
import {isArray, isObject} from "lodash";

/**
 * GET 请求
 * @param url 请求地址
 * @param params 查询参数
 * @returns Promise<Result<T>>
 */
export const getRequest = <T = unknown>(url: string, params?: Recordable) =>
    http.request<T>({url, method: 'GET', params});

/**
 * POST 请求
 * @param url 请求地址
 * @param data 请求体
 * @returns Promise<Result<T>>
 */
export const postRequest = <T = unknown>(url: string, data?: unknown) =>
    http.request<T>({url, method: 'POST', data});


export const postRequestWithHeaders = <T = unknown>(
    url: string,
    data?: unknown,
    header?: object,
    use_cache: boolean = true,
    cache_id: number = 0
) =>
    http.request<T>({
        url,
        method: 'POST',
        data,
        headers: header,
        useCache: use_cache,
        cacheId: cache_id,
    });


/**
 * PUT 请求
 * @param url   接口路径
 * @param params  参数对象 / 单一路径变量
 * @param montage 0 → body/json (默认)
 *                1 → query 字符串拼接
 *                2 → RESTful 路径参数
 */
export const putRequest = <T = unknown>(
    url: string,
    params?: Recordable,
    montage: 0 | 1 | 2 = 0
): Promise<Result<T>> => {
    const safeParams = params || {};
    switch (montage) {
        case 1: {
            // ?key=value 形式
            const query = objectToQueryString(safeParams);
            return http.request({
                url: `${url}?${query}`,
                method: 'PUT',
            });
        }

        case 2: {
            // RESTful /xxx/{id}
            return http.request({
                url: `${url}/${safeParams}`,
                method: 'PUT',
            });
        }

        default: {
            // 默认放到 body
            return http.request({
                url,
                method: 'PUT',
                data: params,
            });
        }
    }
};

/**
 * 智能 POST/PUT 请求
 * - 当 data 包含 id 时自动使用 PUT，否则使用 POST
 * @param url 请求地址
 * @param data 请求体
 * @returns Promise<Result<T>>
 */
export const postOrputRequest = <T = unknown>(url: string, data?: Recordable) => {
    return http.request<T>({url, method: data?.id ? 'PUT' : 'POST', data});
}

/**
 * DELETE 请求
 * @param url 请求地址
 * @param data 请求体（可选，用于 body 参数）
 * @returns Promise<Result<T>>
 */
export const deleteRequest = <T = unknown>(url: string, data?: unknown) => {
    if (!isObject(data) && !isArray(data)) {
        return http.request({
                url: url + '/' + data,
                method: 'DELETE'
            }
        );
    } else {
        return http.request<T>({url, method: 'DELETE', data});
    }
}
